package com.learn.spring_mvc.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;

// @Component
public class HandlerExceptionResolverImpl implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 不管什么异常，都返回统一的异常界面
        // ModelAndView modelAndView = new ModelAndView();
        // modelAndView.setViewName("/error.jsp");
        
        // 区分异常类型，根据不同异常类型响应不同响应体code值，前端根据不同code值跳转不同视图
        int code = 50000;
        String msg = "Exception";
        if (ex instanceof FileNotFoundException) {
            // 自定义code
            code = 50001;
            msg = "FileNotFoundException";
        }
        
        String result = "{\"code\":" + code + ",\"msg\":\"" + msg + "\"}";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return null;
    }
}
